﻿#region Usings

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using FeedReader;
using InfoService.Feeds;
using InfoService.Utils;
using MediaPortal.Configuration;
using MediaPortal.Profile;
using TwitterConnector.OAuth;

#endregion

namespace InfoService.GUIConfiguration
{
    
    public partial class ConfigForm : Form
    {
        private readonly List<ExFeed> feeds = new List<ExFeed>();
        private ExFeed exFeed;
        private bool _authSuccessful;
        private AccessToken _accessToken;

        public ConfigForm()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            /*else if (txtCity.Text == String.Empty || txtCityCode.Text == String.Empty)
            {
                MessageBox.Show("Please add a city for weather service or disable the weather service.", "No weather location", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }*/
            if ((cbFeedEnabled.Checked && lvFeeds.Items.Count <= 0))
            {
                MessageBox.Show("Please add at least one Feed or disable Feed ticker.", "No Feeds", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (cbTwitterEnabled.Checked && (String.IsNullOrEmpty(txtTwitterPIN.Text)))
            {
                MessageBox.Show("Please enter a pin or disable Twitter ticker.", "No pin entered", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                if (cbTwitterEnabled.Checked)
                {
                    if (!cbTwitterFriendsTimeline.Checked && !cbTwitterUserTimeline.Checked &&
                        !cbTwitterPublicTimeline.Checked && !cbTwitterHomeTimeline.Checked &&
                        !cbTwitterRetweetedByMeTimeline.Checked && !cbTwitterRetweetedToMeTimeline.Checked &&
                        !cbTwitterRetweetsOfMeTimeline.Checked && !cbTwitterMentionsTimeline.Checked)
                    {
                        DialogResult dr = MessageBox.Show(
                            "You selected no timeline to update. InfoService will disable the twitter ticker if you continue. Do you want continue?",
                            "Disable twitter ticker?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            cbTwitterEnabled.Checked = false;
                            settings.SetValueAsBool("InfoService", "TwitterTickerEnabled",
                                                    cbTwitterEnabled.Checked ? true : false);
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                if (cbTwitterEnabled.Checked && (!_authSuccessful))
                {
                    DialogResult dr = MessageBox.Show("The last authorization has failed. InfoService will disable the twitter ticker if you continue. Do you want continue?", "Auth unsuccessful", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        cbTwitterEnabled.Checked = false;
                        settings.SetValueAsBool("InfoService", "TwitterTickerEnabled",
                                                cbTwitterEnabled.Checked ? true : false);
                    }
                    else
                    {
                        return;
                    }
                }


                settings.SetValueAsBool("InfoService", "FeedTickerEnabled",  cbFeedEnabled.Checked ? true : false);
                int feednum = 1;
                for (int i = 1; i <= 200; i++)
                {
                    settings.RemoveEntry("InfoService", "Feed" + i + "Url");
                    settings.RemoveEntry("InfoService", "Feed" + i + "Image");
                    settings.RemoveEntry("InfoService", "Feed" + i + "Title");
                    settings.RemoveEntry("InfoService", "Feed" + i + "DefaultZoom");
                }
                for (int index = 1; index < feeds.Count; index++)
                {
                    ExFeed feed = feeds[index];
                    settings.SetValue("InfoService", "Feed" + feednum + "Url", feed.Url);
                    settings.SetValue("InfoService", "Feed" + feednum + "Image", feed.OwnFeedImagePath);
                    settings.SetValue("InfoService", "Feed" + feednum + "Title", feed.OwnFeedTitle);
                    settings.SetValue("InfoService", "Feed" + feednum + "DefaultZoom", feed.DefaultZoom);
                    feednum++;
                }

                settings.SetValueAsBool("InfoService", "FeedRandomFeedOnStartup", rbFeedShowRandomFeedOnStartup.Checked);
                settings.SetValueAsBool("InfoService", "FeedRandomFeedOnUpdate", cbFeedRandomFeedOnUpdate.Checked);
                settings.SetValue("InfoService", "FeedStartupFeedIndex", cobFeedStartupFeed.SelectedIndex);
                settings.SetValue("InfoService", "FeedSeparator", txtFeedSeparator.Text);
                settings.SetValue("InfoService", "FeedItemsCountPerFeed", Convert.ToInt32(txtFeedItemsPerFeed.Value));
                settings.SetValue("InfoService", "FeedItemsCount", Convert.ToInt32(txtFeedItems.Value));
                settings.SetValue("InfoService", "FeedRefreshInterval", Convert.ToInt32(txtFeedRefreshInt.Value));
                settings.SetValueAsBool("InfoService", "FeedUpdateOnStartup", cbFeedUpdateOnStartup.Checked);
                settings.SetValueAsBool("InfoService", "FeedShowItemPublishTime", cbFeedShowItemPublishTime.Checked);
                settings.SetValue("InfoService", "FeedTickerMask", txtFeedTickerLayout.Text);
                
                //settings.SetValueAsBool("InfoService", "FeedShowAllFeedsOnStartup", cbFeedShowAllFeedsOnStartup.Checked);

                //settings.SetValue("InfoService", "FeedZoomStep", Convert.ToInt32(txtFeedZoomStep.Value));

                //settings.SetValue("InfoService", "WeatherLocation", txtCity.Text);
                //settings.SetValue("InfoService", "WeatherLocationCode", txtCityCode.Text);
                //if(cbTempUnit.SelectedIndex == 0) settings.SetValue("InfoService", "WeatherTempUnit", "C");
                //else if (cbTempUnit.SelectedIndex == 1) settings.SetValue("InfoService", "WeatherTempUnit", "F");
                settings.SetValueAsBool("InfoService", "WeatherEnabled", cbWeatherEnabled.Checked ? true : false);
                settings.SetValue("InfoService", "WeatherRefreshInterval", Convert.ToInt32(txtWeatherRefreshInt.Value));
                settings.SetValueAsBool("InfoService", "WeatherUpdateOnStartup", cbWeatherUpdateOnStartup.Checked);

                settings.SetValueAsBool("InfoService", "TwitterTickerEnabled", cbTwitterEnabled.Checked ? true : false);
                if (_authSuccessful)
                {
                    if (_accessToken != null) settings.SetValue("InfoService", "TwitterTokenValue", _accessToken.TokenValue);
                    if (_accessToken != null) settings.SetValue("InfoService", "TwitterTokenSecret", _accessToken.TokenSecret);
                    settings.SetValue("InfoService", "TwitterPin", txtTwitterPIN.Text);
                }
                else
                {
                    if (_accessToken != null) settings.SetValue("InfoService", "TwitterTokenValue", "");
                    if (_accessToken != null) settings.SetValue("InfoService", "TwitterTokenSecret", "");
                    settings.SetValue("InfoService", "TwitterPin", "");  
                }
                settings.SetValue("InfoService", "TwitterSeparator", txtTwitterSeparator.Text);
                settings.SetValue("InfoService", "TwitterItemsCount", Convert.ToInt32(txtTwitterItems.Value));
                settings.SetValue("InfoService", "TwitterRefreshInterval", Convert.ToInt32(txtTwitterRefreshInt.Value));
                settings.SetValueAsBool("InfoService", "TwitterUseUpdateOnStartup", cbTwitterUpdateOnStartup.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUsePublicTimeline", cbTwitterPublicTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseHomeTimeline", cbTwitterHomeTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseUserTimeline", cbTwitterUserTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseFriendsTimeline", cbTwitterFriendsTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseMentionsTimeline", cbTwitterMentionsTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseRetweetedByMeTimeline", cbTwitterRetweetedByMeTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseRetweetedToMeTimeline", cbTwitterRetweetedToMeTimeline.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUseRetweetsOfMeTimeline", cbTwitterRetweetsOfMeTimeline.Checked);
                settings.SetValue("InfoService", "TwitterTickerMask", txtTwitterTickerLayout.Text);
                
                settings.SetValueAsBool("InfoService", "TwitterUpdateStatusOnVideoStart", cbTwitterPostWatchingVideos.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUpdateStatusUsingMovingPictures", cbTwitterUseMovingPictures.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUpdateStatusUsingMPTVSeries", cbTwitterUserTVSeries.Checked);
                settings.SetValueAsBool("InfoService", "TwitterUpdateStatusUsingMyVideo", cbTwitterUseMyVideo.Checked);
                settings.SetValue("InfoService", "TwitterWatchMask", txtTwitterWatchingVideoMask.Text);
            }

            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void cbFeedEnabled_CheckedChanged(object sender, EventArgs e)
        {
            if (cbFeedEnabled.Checked)
            {
                gbFeedConf.Enabled = true;
                gbFeedGeneral.Enabled = true;
                gbFeedTickerLayout.Enabled = true;
                gbFeedLayout.Enabled = true;
            }
            else
            {
                gbFeedConf.Enabled = false;
                gbFeedGeneral.Enabled = false;
                gbFeedTickerLayout.Enabled = false;
                gbFeedLayout.Enabled = false;
            }
        }

        private void cbWeatherEnabled_CheckedChanged(object sender, EventArgs e)
        {
            if (cbWeatherEnabled.Checked)
            {
                gbWeatherGeneral.Enabled = true;
                gbWeatherCity.Enabled = true;
            }
            else
            {
                gbWeatherGeneral.Enabled = false;
                gbWeatherCity.Enabled = false;
            }
        }



        private void ConfigForm_Load(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            cbTempUnit.SelectedIndex = 0;
            XmlDocument xml = new XmlDocument();
            xml.Load(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"));
            if (xml.DocumentElement.SelectSingleNode("//section[@name='InfoService']") == null)
            {
                using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
                {
                    settings.SetValue("InfoService", "Feed1Url", "http://www.team-mediaportal.com/index2.php?option=com_rss&feed=RSS1.0&no_html=1");
                    settings.SetValue("InfoService", "Feed1Image", "");
                    settings.SetValue("InfoService", "Feed1Title", "MediaPortal News");
                    settings.SetValue("InfoService", "Feed1DefaultZoom", "100");
                    settings.SetValueAsBool("InfoService", "FeedTickerEnabled", true);
                    settings.SetValueAsBool("InfoService", "FeedRandomFeedOnUpdate", false);
                    settings.SetValue("InfoService", "FeedDeletionInterval", "Week");
                    settings.SetValue("InfoService", "FeedSeparator", "::");
                    settings.SetValue("InfoService", "FeedItemsCountPerFeed", 3);
                    settings.SetValue("InfoService", "FeedItemsCount", 10);
                    settings.SetValue("InfoService", "FeedRefreshInterval", 30);
                    settings.SetValueAsBool("InfoService", "FeedUpdateOnStartup", true);
                    settings.SetValueAsBool("InfoService", "FeedShowItemPublishTime", true);
                    settings.SetValue("InfoService", "FeedTickerMask", "%itemtitle%");
                    settings.SetValueAsBool("InfoService", "WeatherEnabled", true);
                    settings.SetValue("InfoService", "WeatherRefreshInterval", 60);
                    settings.SetValueAsBool("InfoService", "WeatherUpdateOnStartup", true);
                }
            }
            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                cbFeedEnabled.Checked = settings.GetValueAsBool("InfoService", "FeedTickerEnabled", false);
                cobFeedStartupFeed.Items.Add("All Feeds");
                feeds.Add(new ExFeed("", "All feeds", 0, ""));
                string feedurl = String.Empty;
                string feedimage = String.Empty;
                string feedtitle = String.Empty;
                int feeddefzoom = 0;
                for (int i = 1; i <= 200; i++)
                {
                    feedurl = settings.GetValueAsString("InfoService", "Feed" + i + "Url", "ERROR");
                    if (feedurl == "ERROR") break;
                    feedimage = settings.GetValueAsString("InfoService", "Feed" + i + "Image", " ");
                    feedtitle = settings.GetValueAsString("InfoService", "Feed" + i + "Title", "ERROR");
                    feeddefzoom = settings.GetValueAsInt("InfoService", "Feed" + i + "DefaultZoom", 100);
                    feeds.Add(new ExFeed(feedurl, feedtitle, feeddefzoom, feedimage));
                    lvFeeds.Items.Add(new ListViewItem(new[] {feedtitle, feedurl}));
                    cobFeedStartupFeed.Items.Add(feedtitle);
                }
                exFeed = new ExFeed("http://www.team-mediaportal.com/component/option,com_rss/Itemid,0/feed,RSS2.0/no_html,1/");
                exFeed.Update();
                //cobFeeds.SelectedIndex = cobFeeds.Items.Count - 1;)
                if(settings.GetValueAsBool("InfoService", "FeedRandomFeedOnStartup", false)) rbFeedShowRandomFeedOnStartup.PerformClick();
                else rbFeedShowThisFeedOnStartup.PerformClick();
                cbFeedRandomFeedOnUpdate.Checked = settings.GetValueAsBool("InfoService", "FeedRandomFeedOnUpdate", false);
                cobFeedStartupFeed.SelectedIndex = settings.GetValueAsInt("InfoService", "FeedStartupFeedIndex", 0);
                txtFeedSeparator.Text = settings.GetValueAsString("InfoService", "FeedSeparator", "::");
                txtFeedItems.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "FeedItemsCount", 10));
                txtFeedItemsPerFeed.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "FeedItemsCountPerFeed", 3));
                txtFeedRefreshInt.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "FeedRefreshInterval", 15));
                cbFeedUpdateOnStartup.Checked = settings.GetValueAsBool("InfoService", "FeedUpdateOnStartup", true);
                cbFeedShowItemPublishTime.Checked = settings.GetValueAsBool("InfoService", "FeedShowItemPublishTime", true);
                txtFeedTickerLayout.Text = settings.GetValueAsString("InfoService", "FeedTickerMask", "%itemtitle%");
                
                //cbFeedShowAllFeedsOnStartup.Checked = settings.GetValueAsBool("InfoService", "FeedShowAllFeedsOnStartup", false);
                //txtFeedZoomStep.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "FeedZoomStep", 10));
                cbWeatherEnabled.Checked = settings.GetValueAsBool("InfoService", "WeatherEnabled", false);
                txtWeatherRefreshInt.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "WeatherRefreshInterval", 30));
                cbWeatherUpdateOnStartup.Checked = settings.GetValueAsBool("InfoService", "WeatherUpdateOnStartup", true);
                //txtCity.Text = settings.GetValueAsString("InfoService", "WeatherLocation", "");
                //txtCityCode.Text = settings.GetValueAsString("InfoService","WeatherLocationCode","");
                //if (settings.GetValueAsString("InfoService", "WeatherTempUnit", "") == "C") cbTempUnit.SelectedIndex = 0;
                //else if (settings.GetValueAsString("InfoService", "WeatherTempUnit", "") == "F") cbTempUnit.SelectedIndex = 1;
                //else cbTempUnit.SelectedIndex = 0;
                cbTwitterEnabled.Checked = settings.GetValueAsBool("InfoService", "TwitterTickerEnabled", false);
                txtTwitterPIN.Text = settings.GetValueAsString("InfoService", "TwitterPin", "");
                if(string.IsNullOrEmpty(txtTwitterPIN.Text))
                {
                    txtTwitterPIN.Enabled = true;
                    btnTwitterAuthorize.Enabled = true;
                    _authSuccessful = false;
                }
                else
                {
                    _authSuccessful = true;
                    txtTwitterPIN.Enabled = false;
                    btnTwitterAuthorize.Enabled = false;
                }
                _accessToken = new AccessToken(settings.GetValueAsString("InfoService", "TwitterTokenValue", ""), settings.GetValueAsString("InfoService", "TwitterTokenSecret", ""));
                txtTwitterSeparator.Text = settings.GetValueAsString("InfoService", "TwitterSeparator", "::");
                txtTwitterItems.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "TwitterItemsCount", 10));
                txtTwitterRefreshInt.Value = Convert.ToDecimal(settings.GetValueAsInt("InfoService", "TwitterRefreshInterval", 15));
                cbTwitterUpdateOnStartup.Checked = settings.GetValueAsBool("InfoService", "TwitterUpdateOnStartup", true);
                cbTwitterHomeTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseHomeTimeline", false);
                cbTwitterPublicTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUsePublicTimeline", false);
                cbTwitterUserTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseUserTimeline", false);
                cbTwitterFriendsTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseFriendsTimeline", false);
                cbTwitterMentionsTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseMentionsTimeline", false);
                cbTwitterRetweetedByMeTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseRetweetedByMeTimeline", false);
                cbTwitterRetweetedToMeTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseRetweetedToMeTimeline", false);
                cbTwitterRetweetsOfMeTimeline.Checked = settings.GetValueAsBool("InfoService", "TwitterUseRetweetsOfMeTimeline", false);
                txtTwitterTickerLayout.Text = settings.GetValueAsString("InfoService", "TwitterTickerMask", "%message%");
                cbTwitterPostWatchingVideos.Checked = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusOnVideoStart", false);
                cbTwitterUseMovingPictures.Checked = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMovingPictures", false);
                cbTwitterUserTVSeries.Checked = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMPTVSeries", false);
                cbTwitterUseMyVideo.Checked = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMyVideo", false);
                txtTwitterWatchingVideoMask.Text = settings.GetValueAsString("InfoService", "TwitterWatchMask", "I'm watching %video% on my MediaPortal HTPC!");
                SetExampleTicker();
                lblProductVersion.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                Cursor.Current = Cursors.Default;
            }
            

        }

        private void btnBrowseImage_Click(object sender, EventArgs e)
        {

        }

        private void cbTwitterEnabled_CheckedChanged(object sender, EventArgs e)
        {
            if (cbTwitterEnabled.Checked)
            {
                gbTwitterConf.Enabled = true;
                gbTwitterGeneral.Enabled = true;
                gbTwitterTickerLayout.Enabled = true;
                gbTwitterTimelines.Enabled = true;
                gbTwitterUpdateStatus.Enabled = true;
                gbTwitterLayout.Enabled = true;

            }
            else
            {
                gbTwitterConf.Enabled = false;
                gbTwitterGeneral.Enabled = false;
                gbTwitterTickerLayout.Enabled = false;
                gbTwitterTimelines.Enabled = false;
                gbTwitterUpdateStatus.Enabled = false;
                gbTwitterLayout.Enabled = false;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FeedForm feedform = new FeedForm();
            if (feedform.ShowDialog() == DialogResult.OK)
            {
                lvFeeds.Items.Add(new ListViewItem(new[] { feedform.FeedTitle, feedform.FeedUrl }));
                cobFeedStartupFeed.Items.Add(feedform.FeedTitle);
                feeds.Add(new ExFeed(feedform.FeedUrl, feedform.FeedTitle, feedform.FeedDefaultZoom, feedform.FeedImage));

                //feeds.Add(new Feed(feedform.FeedUrl, feedform.FeedTitle, feedform.FeedImage, feedform.FeedDefaultZoom));
                //lvFeeds.SeSelectedIndex = lv.Items.Count - 1;
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (feeds.Count > 0 && lvFeeds.SelectedIndices.Count > 0)
            {
                int index = lvFeeds.SelectedIndices[0];
                FeedForm feedform = new FeedForm(feeds[index].Url, feeds[index].OwnFeedTitle, feeds[index].OwnFeedImagePath, feeds[index].DefaultZoom);
                if (feedform.ShowDialog() == DialogResult.OK)
                {
                    feeds.RemoveAt(index);
                    feeds.Insert(index, new ExFeed(feedform.FeedUrl, feedform.FeedTitle, feedform.FeedDefaultZoom, feedform.FeedImage ));
                    lvFeeds.Items.RemoveAt(index);
                    lvFeeds.Items.Insert(index, new ListViewItem(new[] { feedform.FeedTitle, feedform.FeedUrl }));
                    //lvFeeds.SelectedIndex = index;
                }
            }
        }

        private void btnRem_Click(object sender, EventArgs e)
        {
            if (feeds.Count > 0 && lvFeeds.SelectedIndices.Count > 0)
            {
                int index = lvFeeds.SelectedIndices[0];
                feeds.RemoveAt(index);
                lvFeeds.Items.RemoveAt(index);
                if ((index - 1) >= 0)
                {
                    if(cobFeedStartupFeed.SelectedIndex == index) cobFeedStartupFeed.SelectedIndex = index - 1;
                    lvFeeds.Items[index - 1].Selected = true;
                }
                cobFeedStartupFeed.Items.RemoveAt(index);
            }

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (txtSearchCity.Text != String.Empty)
            {
                WeatherForm wform = new WeatherForm(txtSearchCity.Text);
                wform.ShowDialog();
                txtCityCode.Text = wform.WeatherLocationCode;
                txtCity.Text = wform.WeatherLocation;
            }
        }
        private void lvFeeds_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvFeeds.SelectedIndices.Count > 0)
            {
                if (lvFeeds.SelectedIndices[0] >= 1)
                {
                    btnEdit.Enabled = true;
                    btnRem.Enabled = true;
                    btnUp.Enabled = lvFeeds.SelectedIndices[0] != 1;
                    btnDown.Enabled = lvFeeds.SelectedIndices[0] != lvFeeds.Items.Count - 1;
                }
                else
                {
                    btnEdit.Enabled = false;
                    btnRem.Enabled = false;
                    btnUp.Enabled = false;
                    btnDown.Enabled = false;
                }
            }
            else
            {
                btnEdit.Enabled = false;
                btnRem.Enabled = false;
                btnUp.Enabled = false;
                btnDown.Enabled = false;
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (feeds.Count > 0 && lvFeeds.SelectedIndices.Count > 0)
            {
                int index = lvFeeds.SelectedIndices[0];
                if ((index - 1) >= 0)
                {
                    ListViewItem itemToMove = lvFeeds.Items[index];
                    object cobItemToMove = cobFeedStartupFeed.Items[index];
                    ExFeed feedToMove = feeds[index];
                    feeds.RemoveAt(index);
                    feeds.Insert(index - 1, feedToMove);
                    lvFeeds.Items.RemoveAt(index);
                    lvFeeds.Items.Insert(index - 1, itemToMove);
                    lvFeeds.Items[index - 1].Selected = true;
                    lvFeeds.EnsureVisible(index - 1);
                    int cobOldSelectedIndex = cobFeedStartupFeed.SelectedIndex;
                    cobFeedStartupFeed.Items.RemoveAt(index);
                    cobFeedStartupFeed.Items.Insert(index - 1, cobItemToMove);
                    if (cobOldSelectedIndex == index) cobFeedStartupFeed.SelectedIndex = index - 1;
                    
                }
                lvFeeds.Select();
                
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (feeds.Count > 0 && lvFeeds.SelectedIndices.Count > 0)
            {
                int index = lvFeeds.SelectedIndices[0];
                if ((index + 1) < lvFeeds.Items.Count && (index + 1) < feeds.Count)
                {
                    ListViewItem itemToMove = lvFeeds.Items[index];
                    object cobItemToMove = cobFeedStartupFeed.Items[index];
                    ExFeed feedToMove = feeds[index];
                    feeds.RemoveAt(index);
                    feeds.Insert(index + 1, feedToMove);
                    lvFeeds.Items.RemoveAt(index);
                    lvFeeds.Items.Insert(index + 1, itemToMove);
                    lvFeeds.Items[index + 1].Selected = true;
                    lvFeeds.EnsureVisible(index + 1);
                    int cobOldSelectedIndex = cobFeedStartupFeed.SelectedIndex;
                    cobFeedStartupFeed.Items.RemoveAt(index);
                    cobFeedStartupFeed.Items.Insert(index + 1, cobItemToMove);
                    if (cobOldSelectedIndex == index) cobFeedStartupFeed.SelectedIndex = index + 1;
                }
                lvFeeds.Select();
            }
        }

        private void txtFeedTickerLayout_TextChanged(object sender, EventArgs e)
        {
            SetExampleTicker();
        }

        private void SetExampleTicker()
        {
            mlFeedTickerExample.Text = FeedUtils.MakeFeedLine(exFeed, txtFeedTickerLayout.Text, 3, txtFeedSeparator.Text);
        }

        private void txtFeedSeparator_TextChanged(object sender, EventArgs e)
        {
            SetExampleTicker();
        }

        private void btnGetPin_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.Cancel ==
                    MessageBox.Show(this, "InfoService will now direct you to the Twitter website where " +
                                          "you will be assigned a 7-digit PIN for this application.",
                                            "InfoService", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
                    return;
                RequestToken requestToken;
                TwitterConnector.Twitter.GetRequestToken(out requestToken);
                Process.Start(TwitterConnector.Twitter.GetAuthUrl());
                _authSuccessful = false;
                btnTwitterAuthorize.Enabled = true;
                txtTwitterPIN.Enabled = true;

            }
            catch (TwitterConnector.Expections.TwitterAuthExpection tae)
            {
                MessageBox.Show(this, "An error occurred during authorization. Error:\n\n" + tae.Message, "InfoService", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "An error occurred during authorization. Error:\n\n" + ex.Message, "InfoService", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void pbOAuthLogo_Click(object sender, EventArgs e)
        {
            Process.Start("http://oauth.net/");
        }

        private void btnAuthorize_Click(object sender, EventArgs e)
        {
            try
            {
                txtTwitterPIN.Text = txtTwitterPIN.Text.Trim();
                if (TwitterConnector.Twitter.GetAuthToken(txtTwitterPIN.Text, out _accessToken))
                {
                    _authSuccessful = true;
                    MessageBox.Show(this, "Successfully authed! You're ready to start tweeting with MediaPortal!", "InfoService", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (TwitterConnector.Expections.TwitterAuthExpection tae)
            {
                MessageBox.Show(this, "An error occurred during authorization. Error: " + tae.Message + "\n\n" + tae.InnerException.Message, "InfoService", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _authSuccessful = false;
            }
            btnTwitterAuthorize.Enabled = false;
            txtTwitterPIN.Enabled = false;
            btnTwitterGetPin.Enabled = true;
        }

        private void cbTwitterPostWatchingVideos_CheckedChanged(object sender, EventArgs e)
        {
            cbTwitterUseMovingPictures.Enabled = cbTwitterPostWatchingVideos.Checked;
            cbTwitterUserTVSeries.Enabled = cbTwitterPostWatchingVideos.Checked;
            cbTwitterUseMyVideo.Enabled = cbTwitterPostWatchingVideos.Checked;
            txtTwitterWatchingVideoMask.Enabled = cbTwitterPostWatchingVideos.Checked;
        }

        private void rbFeedShowThisFeedOnStartup_CheckedChanged(object sender, EventArgs e)
        {
            cobFeedStartupFeed.Enabled = true;
        }

        private void rbFeedShowRandomFeedOnStartup_CheckedChanged(object sender, EventArgs e)
        {
            cobFeedStartupFeed.Enabled = false;
        }

        private void btnAdvancedConfig_Click(object sender, EventArgs e)
        {
            AdvancedConfigForm acf = new AdvancedConfigForm();
            acf.ShowDialog();
        }

        private void llblAboutCodeplex_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://infoservice.codeplex.com/");
        }

        private void llblAboutManual_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://infoservice.codeplex.com/documentation");
        }

        private void llblAboutForum_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://forum.team-mediaportal.com/mediaportal-plugins-47/infoservice-v1-32-5-day-weather-feeds-twitter-basic-home-04-01-2010-planning-60206/");
        }

        private void btnFeedHelp_Click(object sender, EventArgs e)
        {
            Process.Start(@"http://infoservice.codeplex.com/wikipage?title=Feeds%20configuration&referringTitle=How%20to%20use%20%28Users%29");
        }

        private void btnWeatherHelp_Click(object sender, EventArgs e)
        {
            Process.Start(@"http://infoservice.codeplex.com/wikipage?title=Weather%20configuration&referringTitle=How%20to%20use%20%28Users%29");
        }

        private void btnTwitterHelp_Click(object sender, EventArgs e)
        {
            Process.Start(@"http://infoservice.codeplex.com/wikipage?title=Twitter%20configuration&referringTitle=How%20to%20use%20%28Users%29");
        }

        private void llblFamFamFam_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://www.famfamfam.com/");
        }
    }
}
